package com.neu.architecture.controller;

import com.neu.architecture.model.Info;
import com.neu.architecture.service.ArchitectureService;
import com.neu.architecture.util.CommonPage;
import com.neu.architecture.util.CommonResult;
import com.neu.architecture.dto.ResourceParam;
import com.neu.architecture.model.Resource;
import com.neu.architecture.service.ResourceService;
import com.neu.architecture.util.FileItem;
import com.neu.architecture.util.FileStructure;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/api/resource")
@Slf4j
public class ResourceController {

    @Autowired
    ResourceService resourceService;

    @Autowired
    ArchitectureService architectureService;

    @GetMapping("/fetchList")
    public CommonResult<CommonPage<Resource>> fetchList(@RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
                                                        @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) {
        // 根据页大小和页码获取建筑信息列表
        List<Resource> resourceList = resourceService.fetchList(pageSize, pageNum);
        return CommonResult.success(CommonPage.restPage(resourceList));
    }

//    @GetMapping("/searchArchis")
//    public CommonResult<CommonPage<Info>> searchArchis(@RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
//                                                   @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
//                                                   InfoQueryParam param) {
//        System.out.println("param =>" + param);
//        List<Info> architectureList = architectureService.searchArchis(pageSize, pageNum, param);
//        return CommonResult.success(CommonPage.restPage(architectureList));
//    }

    @DeleteMapping("/deleteResource/{id}")
    public CommonResult deleteResource(@PathVariable long id) {
        int count = resourceService.deleteResource(id);
        if (count > 0) {
            return CommonResult.success(true);
        } else {
            return CommonResult.failed("删除失败!");
        }
    }

    @GetMapping("/getResource/{id}")
    public CommonResult<CommonPage<Resource>> getResource(@PathVariable long id) {
        List<Resource> resourceList = resourceService.getResourceById(id);
        return CommonResult.success(CommonPage.restPage(resourceList));
    }

    //@GetMapping("/downloadResource/{id}")
//    public void downloadResource(HttpServletResponse response, @PathVariable long id) {
//        List<Resource> resourceList = resourceService.getResourceById(id);
//        if (resourceList.isEmpty()) {
//            log.error("资源ID不存在 id= {}", id);
//            return;
//        }
//        String path = resourceList.get(0).getPath();
//        if (path == null || path.isEmpty()) {
//            log.error("此id的路径path为空 id= {}", id);
//            return;
//        }
//        String[] sp = path.split("\\\\"); // 正则表达式匹配反斜线，需要四个反斜线，无需奇怪
//        String fileName = sp[sp.length - 1];
////        log.info(fileName);
//        File file = new File(path);
//        if (!file.exists()) {
//            log.error("下载文件不存在, path= {}", path);
//            return;
//        }
//        // response 的配置
//        response.reset();
//        response.setContentType("application/octet-stream");
//        response.setCharacterEncoding("utf-8");
//        response.setContentLength((int) file.length());
//        response.setHeader("Accept-Ranges", "bytes");
//        response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));
//
//        // 打开文件
//        try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file))) {
//            byte[] buff = new byte[1024];
//            OutputStream os = response.getOutputStream();
//            int i = 0;
//            // 将文件读进 buff 中
//            while ((i = bis.read(buff)) != -1) {
//                // 将 buff 中的数据输出到网页
//                os.write(buff, 0, i);
//                // 当 buff 清空?
//                os.flush();
//            }
//        } catch (IOException e) {
//            // 这里的异常原因大多是客户端引起的
//            // e.printStackTrace();
//            // log.error("下载失败");
//        }
//    }

    @GetMapping("/getResourceByInfoId/{id}")
    public CommonResult<CommonPage<Resource>> getResourceByInfoId(@PathVariable long id) {
        List<Resource> resourceList = resourceService.getResourceByInfoId(id);
        return CommonResult.success(CommonPage.restPage(resourceList));
    }

    @PutMapping("/updateResource/{id}")
    public CommonResult updateResource(@PathVariable long id, @RequestBody ResourceParam param) {
        int count = resourceService.updateResource(param, id);
        if (count > 0) {
            return CommonResult.success(true);
        } else {
            return CommonResult.failed("更新失败!");
        }
    }

    @PostMapping("/addResource")
    public CommonResult addResource(@RequestBody Resource resource) {
        int count = resourceService.addResource(resource);
        if (count > 0) {
            return CommonResult.success(true);
        } else {
            return CommonResult.failed("更新失败!");
        }
    }

    @GetMapping("/downloadResource/{id}")
    public void downloadResource(HttpServletResponse response, @PathVariable long id, @RequestParam String filename) {

        List<Info> archiById = architectureService.getArchiById(id);
        String city = archiById.get(0).getCity();
        String name = archiById.get(0).getName();
        filename = filename.replace(",", "\\");
        String path = FileStructure.getPath(city, name, filename);
        File file = new File(path);

        if (!file.exists()) {
            log.error("下载文件不存在, path= {}", path);
            return;
        }

        // response 的配置
        response.reset();
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        response.setContentLength((int) file.length());
        response.setHeader("Accept-Ranges", "bytes");
        response.setHeader("Content-Disposition", "attachment;filename=" + new String(file.getName().getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));

        // 打开文件
        try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file))) {
            byte[] buff = new byte[1024];
            OutputStream os = response.getOutputStream();
            int i = 0;
            // 将文件读进 buff 中
            while ((i = bis.read(buff)) != -1) {
                // 将 buff 中的数据输出到网页
                os.write(buff, 0, i);
                // 当 buff 清空?
                os.flush();
            }
        } catch (IOException e) {
            // 这里的异常原因大多是客户端引起的
            // e.printStackTrace();
            // log.error("下载失败");
        }
    }

    @GetMapping("/getFileTree/{id}")
    public CommonResult<List<FileItem>> getFileTree(@PathVariable long id, @RequestParam String type) {
        List<Info> archiById = architectureService.getArchiById(id);
        String city = archiById.get(0).getCity();
        String name = archiById.get(0).getName();
        String path = FileStructure.getPath(city, name, type);
        File file = new File(path);
        if (file.listFiles() == null) {
            return CommonResult.failed("file 为空, path 为: " + path);
        }
        return CommonResult.success(FileStructure.traverseDir(new File(path)));
    }

    @GetMapping("/getImg/{id}")
    public CommonResult<String> getImg(@PathVariable long id) {
        List<Info> archiById = architectureService.getArchiById(id);
        String city = archiById.get(0).getCity();
        String name = archiById.get(0).getName();
        String name1 = "";
        if (name.endsWith("旧址")) {
            name1 = name.replace("旧址" ,"");
        }
        String type = "效果图图像";
        String path = FileStructure.getPath(city, name, type);
        System.out.println(path);
        File file = new File(path);
        if (file.listFiles() != null) {
            for (File file1 : Objects.requireNonNull(file.listFiles())) {
                if (file1.getName().contains("鸟瞰图")) {
                    if (file1.listFiles() != null) {
                        String imgName = Objects.requireNonNull(file1.listFiles())[0].getName();
                        String path1 = "http://localhost:8080/api/resource/downloadResource/" + id + "?filename=效果图图像," + file1.getName() + "," + imgName;
                        return CommonResult.success(path1);
                    } else {
                        String imgName = file1.getName();
                        String path1 = "http://localhost:8080/api/resource/downloadResource/" + id + "?filename=效果图图像," + imgName;
                        return CommonResult.success(path1);
                    }
                }
            }
        }
        return CommonResult.failed("没找到鸟瞰图");
    }
}
